package com.scrawler.main;




import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.PropertyConfigurator;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.stereotype.Service;

import com.scrawler.util.ConstantUtils;
import com.scrawler.util.PathUtil;

@Service
public class InitProject{
	private static final Log LOG = LogFactory.getLog(InitProject.class);
	private  static  FileSystemXmlApplicationContext baseContext; 
	// 有注解的类,必须交给spring来管理

	public static void init(){
		String logOutputPath = PathUtil.getInstance().getBasePath();
		/** 设置输出日志的环境变量地址*/
		System.setProperty("log_output_dir",logOutputPath);
		//DOMConfigurator.configure(log4jPath);//XML配置文件		
		/** 初始化log4j  */
		String basePath = PathUtil.getInstance().getBasePath();
		String log4jPath =basePath+ConstantUtils.CONFIG_FILE_LOG4J;
		PropertyConfigurator.configure(log4jPath);
		LOG.info("basePath: "+basePath);
		LOG.info("set log output path: "+logOutputPath);
		LOG.info("log4j config file path: "+log4jPath);
		LOG.info("Initializing log4j ok........");
		/** init Spring config*/
		String springConfigFilePath = basePath+ConstantUtils.CONFIG_FILE_SPRING;
		String targetPath = null;		
		try{
			if(PathUtil.getInstance().getOsName().toLowerCase().contains("windows")){
				//windows下
				baseContext = new FileSystemXmlApplicationContext(springConfigFilePath);		
				targetPath = springConfigFilePath;
			}
			else{
				// linux下
				 baseContext = new FileSystemXmlApplicationContext(ConstantUtils.CONFIG_FILE_SPRING);
				 targetPath = ConstantUtils.CONFIG_FILE_SPRING;
			}
		}catch(Exception e){
			LOG.error("load spring xml error..."+e);
			
		}
		LOG.info("Initializing spring ok......,spring config file path:"+targetPath);
		 LOG.info("Initializing redis pool ok.......");
		// 在JVM里注册一个“关闭钩子”（shutdown hook）
		// baseContext.registerShutdownHook();
	}

	public  static FileSystemXmlApplicationContext getContext(){
		return baseContext;
	}

}
